import xml.dom.minidom as Dom
import os
import sys

suffix = '.xml'

# TODO:hive spark路径完善
HADOOP_CONF_DIR = os.environ.get('HADOOP_CONF_DIR') if os.environ.get(
    'HADOOP_CONF_DIR') else str.format('/opt/hadoop-{}/etc/hadoop', os.environ.get('HADOOP_VERSION'))
HIVE_CONF_DIR = os.environ.get('HIVE_CONF_DIR') if os.environ.get(
    'HIVE_CONF_DIR') else str.format('/opt/hive-{}/conf', os.environ.get('HIVE_VERSION'))
SPARK_CONF_DIR = os.environ.get('SPARK_CONF_DIR') if os.environ.get(
    'SPARK_CONF_DIR') else str.format('/opt/spark-{}/conf', os.environ.get('SPARK_VERSION'))

conf_dir = {
    'core-site': HADOOP_CONF_DIR,
    'hdfs-site': HADOOP_CONF_DIR,
    'mapred-site': HADOOP_CONF_DIR,
    'yarn-site': HADOOP_CONF_DIR,
    'hive-site': HIVE_CONF_DIR,
    'spark-defaults': SPARK_CONF_DIR,
}


def print_usage():
    print("""
  Usage: python setConf.py conf_name

  eg: core-site hadoop-env hdfs-site mapred-site oozie-site spark-defaults yarn-site
  """)
    exit(1)


def add_property(string: str, root: Dom.Node, doc: Dom.Document):
    kv = string.replace('\n', '').split('=')
    prop = doc.createElement('property')
    name = doc.createElement('name')
    value = doc.createElement('value')
    root.appendChild(prop)
    name.appendChild(doc.createTextNode(kv[0]))
    value.appendChild(doc.createTextNode(kv[1]))
    prop.appendChild(name)
    prop.appendChild(value)


def save_xml(prefix: str, doc: Dom.Document):
    """
    如果系统为win生成路径为当前项目根目录
    """
    if check_os() == 1:
        conf_path = prefix + suffix
    else:
        conf_path = str.format("{}/{}", conf_dir.get(prefix), prefix + suffix)
    check_exists(conf_path)
    with open(conf_path, 'w', encoding='utf-8') as f:
        doc.writexml(f, addindent='  ', newl='\n', encoding='utf-8')
    print(str.format("文件写入 {} 成功。", conf_path))


def check_os():
    """
    1:windows 2:linux 3:macos
    """
    os_type = os.environ.get('OS')
    if os_type and 'Windows' in os_type:
        return 1
    elif os_type and 'Linux' in os_type:
        return 2
    elif os_type and 'Mac' in os_type:
        return 3
    else:
        return 2


def check_exists(file_name):
    if os.path.exists(file_name):
        os.remove(file_name)


if __name__ == "__main__":
    if len(sys.argv) > 1 and sys.argv[1] in conf_dir:
        prefix = sys.argv[1]
        print(str.format("生成配置文件:{}", sys.argv[1]))
    else:
        print_usage()

    if check_os() == 1:
        filepath = os.path.join(
            os.environ['HOMEPATH'], "C:\\Users\\rainb-yss\\Downloads\\压缩包\\hadoop-3.1.3\\etc\\hadoop", prefix + suffix)
    else:
        filepath = str.format("{}/{}", conf_dir.get(prefix), prefix + suffix)

    if os.path.exists(filepath):
        doc = Dom.parse(filepath)
        root: Dom.Node = doc.lastChild
        for i in root.childNodes:
            root.removeChild(i)
    else:
        doc = Dom.Document()
        xlstNode = doc.createProcessingInstruction(
            'xml-stylesheet', 'type=\"text/xsl\" href=\"configuration.xsl\"')
        root = doc.createElement('configuration')
        doc.appendChild(xlstNode)
        doc.appendChild(root)

    properties_dir = os.path.dirname(__file__)
    with open(str.format('{}/{}', properties_dir, 'conf.properties'), 'r', encoding='utf-8') as f:
        for line in f.readlines():
            if line.startswith(prefix):
                print('set ',line)
                add_property(line.replace(prefix + '_', ''), root, doc)

    save_xml(prefix, doc)
